package world.ztomorrow.user.utils;

import com.github.benmanes.caffeine.cache.Cache;
import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;
import java.util.function.Function;


@Component
@RequiredArgsConstructor
public class CacheUtils {

    private  final  Cache<String, Object> caffeineOne;
    private final StringRedisTemplate stringRedisTemplate;



    public <T> T getCacheOne(Function<Object, T> Function,
                             String localKey, String redisKey,
                             Function<String, T> fromStringFunction){
        // 先从本地缓存取
        Object localCache = caffeineOne.getIfPresent(localKey);
        // 命中返回，并刷新过期时间
        if (localCache != null) {
            return Function.apply(localCache);
        }
        // 未命中，从redis中获取数据
        String RedisCache = stringRedisTemplate.opsForValue().get(redisKey);
        // 命中返回，并刷新过期时间
        if (RedisCache != null && !RedisCache.isEmpty()) {
            return fromStringFunction.apply(RedisCache);
        }
        return null;
    }


    public <T> void saveCacheOne( T obj, String localKey, String redisKey,
                                  long expireTime, Function<Object, String> fromStringFunction){
        caffeineOne.put(localKey, obj);
        stringRedisTemplate.opsForValue().set(redisKey, fromStringFunction.apply(obj),
                expireTime, TimeUnit.MINUTES);
    }

    public void clearCache(String localKey, String redisKey) {
        caffeineOne.invalidate(localKey);
        stringRedisTemplate.delete(redisKey);
    }
}
